package io.renren.modules.member.service.impl;

import io.renren.modules.member.rfid.RFIDReaderHelper;
import io.renren.modules.member.rfid.ReaderConnector;
import io.renren.modules.member.rfid.ReaderHelper;
import io.renren.modules.member.rfid.RfidTool;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("rfidModifyService")
public class RfidModifyService {

    private static final List<ReaderConnector> connetList = new ArrayList<>();

    public String openRfid(String com) {
        if (!CollectionUtils.isEmpty(connetList)) {
            return null;
        }
        ReaderHelper mReaderHelper = null;
        try {
            mReaderHelper = openConnect(com);
        } catch (Exception e) {
            e.printStackTrace();
            return "打开读卡器失败，请确认COM口是否正确、读卡器是否正常连接!";
        }
        if (Objects.isNull(mReaderHelper)) {
            return "打开读卡器失败，请确认COM口是否正确、读卡器是否正常连接!";
        } else {
            return null;
        }
//        new Thread() {
//            @Override
//            public void run() {
//                openConnect(com);
//            }
//        }.start();
    }

    private ReaderHelper openConnect(String port) {
        final ReaderConnector mConnector = new ReaderConnector();
        ReaderHelper mReaderHelper = mConnector.connectCom(port, 115200); //here "COM7" ，you need to change your serial-port Number！！
        if(mReaderHelper != null) {
            connetList.add(mConnector);
            RfidTool.mReaderHelper = mReaderHelper;
            mReaderHelper.registerObserver(RfidTool.mObserver);
            mReaderHelper.setRXTXListener(RfidTool.mListener);
            ((RFIDReaderHelper) mReaderHelper).realTimeInventory((byte) 0xff,(byte)0x01);
        } else {
            mConnector.disConnect();
        }
        return mReaderHelper;
    }


    public String closeRfid() {
        if (!CollectionUtils.isEmpty(connetList)) {
            for (ReaderConnector connector : connetList) {
                connector.disConnect();
            }
            connetList.clear();
            return "关闭读卡器成功!";
        } else {
            return "没有链接的读卡器需要关闭!";
        }
    }
}
